﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GoShopping.Model;

namespace GoShopping.BLL.PrdctInfo
{
    /// <summary>
    /// 打折商品操作类
    /// </summary>
    public class DiscountPrdctBean
    {
        /// <summary>
        /// 静态类做缓存
        /// </summary>
        private static IList<DiscountPrdct> _AllDiscountPrdctList;

        /// <summary>
        /// 取出所有列表
        /// </summary>
        /// <returns></returns>
        public IList<DiscountPrdct> GetAll()
        {
            _AllDiscountPrdctList = Databases.DBGoShopping.Select(
                GoShoppingNBear.DiscountPrdct).ToList<DiscountPrdct>();
            return _AllDiscountPrdctList;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        public void DelDiscountPrdct(int id)
        {
            Databases.DBGoShopping.Delete(
                GoShoppingNBear.DiscountPrdct).Where(
                GoShoppingNBear.DiscountPrdct.ID == id).Execute();

            GetAll();
        }

        /// <summary>
        /// 添加一个
        /// </summary>
        /// <param name="dp"></param>
        /// <returns>返回添加到结果的ID</returns>
        public int AddOne(DiscountPrdct dp)
        {
            return Databases.DBGoShopping.Insert(GoShoppingNBear.DiscountPrdct).AddColumn(
                GoShoppingNBear.DiscountPrdct.PrdctID, dp.PrdctID).AddColumn(
                GoShoppingNBear.DiscountPrdct.DiscountPrice, dp.DiscountPrice).AddColumn(
                GoShoppingNBear.DiscountPrdct.EndDate, dp.EndDate).AddColumn(
                GoShoppingNBear.DiscountPrdct.StartDate, dp.StartDate).ExecuteReturnAutoIncrementID(
                GoShoppingNBear.DiscountPrdct.ID);

            GetAll();
        }

        /// <summary>
        /// 判断一个商品在一个时间里是否有折扣
        /// </summary>
        /// <param name="prdctID"></param>
        /// <param name="dt"></param>
        /// <returns>如果有，则discountPrdct返回该条数据</returns>
        public bool IsPrdctHasDiscount(int prdctID, DateTime dt, out DiscountPrdct discountPrdct)
        {
            if (_AllDiscountPrdctList == null)
            {
                GetAll();
            }
            foreach (DiscountPrdct d in _AllDiscountPrdctList)
            {
                if (d.PrdctID == prdctID && d.StartDate <= dt && d.EndDate >= dt)
                {
                    discountPrdct = d;
                    return true;
                }
            }
            discountPrdct = null;
            return false;
        }
    }
}
